# coding:utf-8

from django.db import models
from django.core.urlresolvers import reverse
from collections import OrderedDict

# Create your models here.

"""
定义作者信息，包括姓名、电子邮件、个人网站等信息
"""
class Author(models.Model):
	name = models.CharField(max_length = 30)
	email = models.EmailField(blank = True)
	website = models.URLField(blank = True)

	def __unicode__(self):
		return self.name

"""
标签管理器
"""
class TagManager(models.Manager):

	# 返回文章标签列表，每个标签以及对应的文章数目
	def get_Tag_List(self):

		# 获取所有标签
		tags = Tag.objects.all()
		# tagInfoArray实际为二维数组，不同的行对应不同的标签，行中包含标签名和对应文章数目
		tagInfoArray = []

		for i in range(len(tags)):
			tagInfo = []
			# 获取当前标签
			currentTag = Tag.objects.get(name = tags[i])
			# 获取当前标签下的所有文章
			articles = currentTag.article_set.all()
			tagInfo.append(currentTag.name)
			tagInfo.append(len(articles))
			tagInfoArray.append(tagInfo)

		return tagInfoArray

"""
标签
"""
class Tag(models.Model):
	name = models.CharField(max_length = 20, blank = True)
	create_time = models.DateField(auto_now_add = True)

	objects = models.Manager()
	tag_list = TagManager()

	@models.permalink
	def get_absolute_url(self):
		return ('tagDetail', (), {'tag':self.name})

	def __unicode__(self):
		return self.name

"""
分类管理器
"""
class ClassManager(models.Manager):

	# 返回文章分类列表，每个分类以及对应的文章数目
	def get_Class_List(self):

		# 获取所有的分类
		classes = Classification.objects.all()
		# class_list实际为一个二维数组，不同的行对应不同的分类，行中包含分类名和对应文章数目
		classInfoArray = []

		for i in range(len(classes)):
			classInfo = []
			currentClass = Classification.objects.get(name = classes[i])
			posts = currentClass.article_set.all()
			classInfo.append(currentClass.name)
			classInfo.append(len(posts))
			classInfoArray.append(classInfo)

		return classInfoArray

"""
分类
"""
class Classification(models.Model):
	name = models.CharField(max_length = 50)

	objects = models.Manager()
	class_list = ClassManager()

	def __unicode__(self):
		return self.name

"""
文章管理器
"""
class ArticleManager(models.Manager):

	# 实现文章的按月归档，返回月份以及对应的文章数，如[[2015.5, 5], [2015.4, 10]]
	def get_Articles_onMonth(self):
		# dates(field, kind, order): Returns a special QuerySet that evaluates to a list of datetime.datetime objects
		# representing all available dates of a particular kind within the content of the QuerySet.
		# For example, dates('publish_time','year')==> [2013.3, 2013.5, 2014.2, 2012.3] -> [2012, 2013, 2014]
		post_date = Article.objects.dates('publish_time', 'month')
		# post_date = post_date.reverse() # 逆置post_date，使之按月份递减，此处可以通过class Mate实现
		dateArticleArray = []

		for i in range(len(post_date)):
			dateArticle = []
			curyear = post_date[i].year
			curmonth = post_date[i].month
			tempArticles = Article.objects.filter(publish_time__year=curyear).filter(publish_time__month=curmonth)
			dateArticle.append(post_date[i])
			dateArticle.append(len(tempArticles))
			dateArticleArray.append(dateArticle)
			
		return dateArticleArray

	# 返回一个字典，一个时间点，对应一个文章列表
	def get_Articles_onArchive(self):
		post_date = Article.objects.dates('publish_time', 'month')
		archiveDicts = OrderedDict()

		for i in range(len(post_date)):
			curyear = post_date[i].year
			curmonth = post_date[i].month
			tempArticle = Article.objects.filter(publish_time__year=curyear).filter(publish_time__month=curmonth)
			archiveDicts.setdefault(post_date[i], tempArticle)

		return archiveDicts

"""
文章类
"""
class Article(models.Model):
	title = models.CharField(max_length = 100)
	# 如果公共关键字在一个关系中是主关键字，那么这个公共关键字就被称为另一个关系的外键。
	# 外键表示了两个关系之间的相关联系。
	author = models.ForeignKey(Author)
	# 多对多字段，表示一篇文章有一个或多个标签，但是Article数据库表中并没有tags字段。
	# 相反，Django创建了一个额外的多对多连接表由于处理文章和标签之间的映射关系
	# 标签
	tags = models.ManyToManyField(Tag, blank = True)
	# 分类
	classification = models.ForeignKey(Classification)
	# 文章内容
	content = models.TextField(blank = True, null = True)
	# 发布时间
	publish_time = models.DateField(auto_now_add = True)
	# 文章点击数
	count = models.IntegerField(default = 0)

	objects = models.Manager()
	article_list = ArticleManager()

	@models.permalink
	def get_absolute_url(self):
		return ('detail', (), {
			'year': self.publish_time.year,
			'month': self.publish_time.strftime('%m'),
			'day': self.publish_time.strftime('%d'),
			'id': self.id
			})

	# 返回一篇文章对应的所有标签
	def get_tags(self):
		taglist = self.tags.all()
		return taglist

	# 返回当前文章的前一篇文章
	def get_prev_article(self):
		temp = Article.objects.order_by('id')
		index = 0
		for t in temp:
			if t.id == self.id:
				break
			else:
				index = index + 1
		if index != 0:
			return temp[index - 1]

	# 返回当前文章的后一篇文章
	def get_next_article(self):
		temp = Article.objects.order_by('id')
		max = len(temp) - 1
		index = 0
		for t in temp:
			if t.id == self.id:
				break
			else:
				index = index + 1
		if index != max:
			return temp[index + 1]

	def __unicode__(self):
		return self.title

	# 按时间下降排序
	class Meta:
		ordering = ['-publish_time']